﻿@*2020版 中途结算*@
@using Newtouch.Infrastructure;
@{
    ViewBag.Title = "PartialSettleIndex2021";
    Layout = "~/Views/Shared/_Form.cshtml";

    //是否和医保交易
    var openYbSett = SysConfigReader.Bool("Inpatient_Sett_OpenYbSett");
    //医保所属地，区分系统将执行何处医保逻辑
    var medicalInsurance = SysConfigReader.String("Outpatient_MedicalInsurance");

    //收费成功之后是否直接打印收据
    var autoPrintFP = SysConfigReader.Bool("Inpatient_Sett_AutoPrint");
    //收据报表链接
    var invoiceReportUrl = SysConfigReader.OrgReportLink("NewInpatientSetts");

    var opr = Newtouch.Common.Operator.OperatorProvider.GetCurrent();
    var yesterday = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 23:59:59");
}

@Html.Partial("_YibaoCommonView")
<div class="rows" style="margin-bottom: 1%;">
    <div class="panel panel-default" style="margin-bottom:0;">
        <div class="panel-heading navb-bg">
            住院患者信息
        </div>
        <table class="form" style="width:96%;">
            <tbody>
                <tr>
                    <th class="formTitle">住院号：</th>
                    <td class="formValue">
                        <input class="form-control" type="text" id="zyh" value="" />
                    </td>
                    <td class="formValue">
                        <input type="button" class="btn btn-default btn-md btn-default-color" title="选择住院患者" style="" id="zy_btnsyy" value="查询" onclick="GetPatSerarchView();">
                    </td>
                    <td class="formValue" style="width: 130px">
                        @if (openYbSett == true)
                        {
                            @Html.Partial("YibaoRedCardCommon")
                        }
                    </td>
                    <th class="formTitle" style="width: 50px">开始时间：</th>
                    <td class="formValue" style="width:143px;">
                        <label id="startTime"></label>
                    </td>
                    <th class="formTitle">结束时间：</th>
                    <td class="formValue" style="width:143px;">
                        <input id="endTime" type="text" class="form-control input-wdatepicker form-an formClearIgnore"
                               onfocus="WdatePicker({ dateFmt: 'yyyy-MM-dd HH:mm:ss', onpicked: function () { thenreload(); } })" value="@DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")" />
                    </td>
                    <th class="formTitle">姓名：</th>
                    <td class="formValue">
                        <label id="zy_xm" style="min-width:100px"></label>
                    </td>
                    <th class="formTitle">性别：</th>
                    <td class="formValue">
                        <label id="zy_xb"></label>
                    </td>
                </tr>
            </tbody>
            <tbody class="dispTbody" style="display:none;">
                <tr>
                    <th class="formTitle"></th>
                    <td class="formValue" colspan="3">
                        <label></label>
                    </td>
                    
                    <th class="formTitle">年龄：</th>
                    <td class="formValue">
                        <label id="zy_nl"></label>
                    </td>
                    <th class="formTitle">入院诊断：</th>
                    <td class="formValue">
                        <label id="zy_ryzd"></label>
                    </td>
                    <th class="formTitle">出生日期：</th>
                    <td class="formValue" >
                        <label id="zy_csny" style="min-width:100px"></label>
                    </td>
                    <th class="formTitle">入院日期：</th>
                    <td class="formValue">
                        <label id="zy_ryrq" style="min-width:100px"></label>
                    </td>
                </tr>
            </tbody>
        </table>
        <div class="fa_icontoggle"><i class="fa fa-angle-double-down icontoggle" style="color:rgb(0, 160, 233);cursor:pointer;"></i></div>
    </div>
</div>
<ul id="myTab" class="nav nav-tabs">
    <li class="active"><a href="#wj" data-toggle="tab">未结费用</a></li>
    <li><a href="#yj" data-toggle="tab">历史已结</a></li>
</ul>
<div id="myTabContent" class="tab-content">
    <div class="tab-pane fade in active" id="wj">
        <div class="gridPanel">
            <table id="gridList"></table>
        </div>
    </div>
    <div class="tab-pane fade" id="yj">
        <div class="gridPanel">
            <table id="gridList2"></table>
        </div>
        <div style="margin:3px 0;">
            <span style="color:red;font-weight:bold;">*.撤销功能限制为撤销列表中最后一次结算</span>
        </div>
    </div>
</div>

<div class="rows" style="margin-bottom: 1%;margin-top: 1%;">
    <div class="panel panel-default" style="margin-bottom:0;padding:10px;">
        <table class="form" style="width:96%;">
            <tbody>
                <tr>
                    <th class="formTitle">未结费用：</th>
                    <td class="formValue" style="width:100px;">
                        <label id="lblSumje" style="color:red;font-weight: bold;font-size: large;"></label>
                    </td>
                    <th class="formTitle" style="width:105px;">上次结算结束时间：</th>
                    <td class="formValue">
                        <label id="lastValidMidwaySettTime"></label>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
@Html.Partial("_BottomButtonsView", new Newtouch.HIS.Web.Core.Models.BottomButtonViewModel()
{
    ShowKeyList = new int[] { 6,7, 8 },
    F8Text = "确认收费",
    F6Text = "撤销结算",
    F7Text = "转出院结算",
    F6Hidden = true,
    F7Hidden = true,
    F8Hidden = true,
})
<script type="text/javascript">
    var openYbSett = '@openYbSett' === 'True'; //开关配置：医保患者是否使用医保交易流程
    var isYbjyjz; //当前是否走医保交易的就诊
    var medicalInsurance = '@medicalInsurance';
    var curTime = $.getDate() + " 23:59:59";

    var ybkCardType = "@((int)EnumCardType.YBJYK)";//医保卡类型
    var xnkCardType = "@((int)EnumCardType.XNK)";//虚拟卡类型
    var ybCommonBackReturnData;//医保撤销最后一次结算结果
    var ybIsReadCard = false;
    var zyh;

    //通过ls把住院号传过去
    var fromzyh = sessionStorage.getItem('zyh');
    var defaultShow = sessionStorage.getItem('defaultShow');
    $("#readCard").show();
    if (fromzyh) {
        $('#zyh').val(fromzyh);
        zyh = fromzyh;
        sessionStorage.removeItem('zyh');
    }
    if (defaultShow) {
        sessionStorage.removeItem('defaultShow');
    }

    $(function () {
        initgridList1();
        initgridList2();
        $('#myTab li:eq(1) a').tab('show'); //会触发grid2加载样式

        if (!(defaultShow === 'yj')) {
            setTimeout("$('#myTab li:eq(0) a').tab('show');", 200); //显示未结
        }
    });

    function initgridList1() {
        if ($('#startTime').val() > $('#endTime').val()) {
            $.modalAlert("开始时间不能大于结束时间", "warning");
            return;
        }
        $('#gridList').dataGrid({
            unwritten: false,
            url: "/HospitalizationManage/BookkeepInHos/GetUnSettedFeeItemListJson",
            postData: { zyh: zyh, endTime: $("#endTime").val() ,ver:'2'},
            height: $(window).height() - 290,
            sortable: false,
            colModel: [
                { label: "收费项目名称", name: "sfxmmc", width: 180, align: "left" },
                {
                    label: "数量", name: "sl", width: 80, align: "left", formatter: "number"
                    , formatoptions: { decimalPlaces: 2, defaultValue: '0.00' }
                },
                {
                    label: "总金额", name: "zje", width: 80, align: "left", formatter: "number"
                        , formatoptions: { decimalPlaces: 2, defaultValue: '0.00' }
                },
            ],
            gridComplete: function (data) {
                var sumje = 0;
                if (data&&data.length > 0) {
                    $.each(data, function () {
                        sumje += this.zje;
                    });
                    if (sumje != 0) {
                        $('#lblSumje').html(sumje.toFixed(2));
                    }
                    else {
                        $('#lblSumje').html('');
                    }
                }
                jszje = sumje.toFixed(2);
            }
        });
    }

    var flagIsFirstInitGrid2 = true;
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        var targetHref = $(e.target).attr('href');
        $('#btn_bottombutton_f6,#btn_bottombutton_f7,#btn_bottombutton_f8').hide();
        if (targetHref && targetHref.indexOf('yj') != -1) {
            $('#btn_bottombutton_f6,#btn_bottombutton_f7').show();
            if (flagIsFirstInitGrid2) {
                flagIsFirstInitGrid2 = false;
            }
            reloadGrid2();
        }
        else {
            $('#btn_bottombutton_f8').show();
        }
    })

    function initgridList2() {
        $('#gridList2').dataGrid({
            unwritten: false,
            height: $(window).height() - 310,
            sortable: false,
            colModel: [
                { label: "jsnm", name: "jsnm", align: "left", hidden: true },
                { label: "住院号", name: "zyh", align: "left", hidden: true },
                {
                    label: "结算金额", name: "zje", width: 180, align: "left", formatter: "number"
                    , formatoptions: { decimalPlaces: 2, defaultValue: '0.00' }
                },
                {
                    label: "结算开始时间", name: "jsksrq", width: 240, align: "left",
                    formatter: "date", formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s' }
                },
                {
                    label: "结算结束时间", name: "jsjsrq", width: 240, align: "left",
                    formatter: "date", formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s' }
                },
                { label: "结算人员", name: "CreatorCode", width: 140, align: "left" },
                {
                    label: "结算时间", name: "CreateTime", width: 240, align: "left",
                    formatter: "date", formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s' }
                }
            ],
        });
    }

    function thenreload() {
        //加载未结
        reloadGrid();
        reloadLastValidMidwaySettTime();

        var targetHref = $('#myTab li.active a').attr('href');
        if (targetHref && targetHref.indexOf('yj') != -1) {
            reloadGrid2();  //当前已是已结
        }
    }

    function reloadGrid() {
        if ($("#startTime").val() > $("#endTime").val()) {
            $.modalAlert("开始时间不能大于结束时间", "warning");
            return;
        }
        $("#gridList").jqGrid('setGridParam', {
            postData: { zyh: zyh, endTime: $("#endTime").val() },
        }).trigger('reloadGrid');

    }

    function reloadGrid2() {
        $("#gridList2").jqGrid('setGridParam', {
            postData: { zyh: zyh },
            url:"/HospitalizationManage/BookkeepInHos/GetMidwaySettedListJson"
        }).trigger('reloadGrid');

    }

    function reloadLastValidMidwaySettTime() {
        //更新‘最后结算结束时间’
        $('#lastValidMidwaySettTime').html('');
        if (!!zyh) {
            $.najax({
                url: "/HospitalizationManage/BookkeepInHos/GetLastValidMidwaySettTimeJson?zyh=" + zyh,
                success: function (ajaxresp) {
                    if (ajaxresp.data) {
                        $('#lastValidMidwaySettTime').html($.getTime({ date: ajaxresp.data }));
                        $('#startTime').html($.getTime({ date: ajaxresp.data }));
                    }
                },
            });
        }
    }

    //病人查询
    function GetPatSerarchView() {
        $.modalOpen({
            id: "patSearch",
            title: "患者查询",
            url: "/PatientManage/AccountManage/PatSearchView?brzybzType=" + '@((int)EnumZYBZ.Bqz + "," + (int)EnumZYBZ.Djz)' + "&t=" + Math.random() + "&zyh=" + zyh,
            width: "700px",
            height: "600px",
            callBack: function (iframeId) {
                top.frames[iframeId].PatDbGrid(); //在弹出窗口事件
                //调用查询卡号和住院号
            }//窗口点确定的回调函数
        });

    }

    //手输社保卡号
    function GetPatSbkh() {
        $.modalOpen({
            id: "sbkhInput",
            title: "卡号输入",
            url: "/OutpatientManage/OutpatientReg/OutPatientSbkhInput?t=" + Math.random(),
            width: "300px",
            height: "150px",
            callBack: function (iframeId) {
                top.frames[iframeId].PatSbkhData();
            }
        });
    }
    //选择的病人 callback
    function getPatInfoAjax(selePatInfo) {
        $('#endTime').val('@(yesterday)'); //update endTime
        $('#zyh').val(selePatInfo.zyh);
        zyh = selePatInfo.zyh;
        ajaxLoadDataResult({ zyh: selePatInfo.zyh});
    }

    var patModel = null;
    var jszje = 0.00;
    //加载住院基本信息
    function ajaxLoadDataResult(obj, funcSuccCallback) {
        $('#startTime').html('');   //只有切换住院号的时候，才切换开始日期
            $.najax({
                type: "POST",
                data: obj,
                url: "/HospitalizationManage/DischargeSettle/GetPartialInpatientSettleStatusDetail",
                dataType: "json",
                success: function (ajaxresp) {
                    $('#lblSumje').text('0.00');
                    patModel = ajaxresp.data.InpatientSettPatInfo
                    cqPatInfo.zymzh = patModel.zyh;//住院号
                    setPatInfoModel();

                    thenreload();
                    isYbjyjz = openYbSett && (patModel.brxz != '0' && patModel.brxz != 'yb3' && patModel.brxz != 'yb6' && patModel.brxz != 'yb25');

                },
                errorCallback: function (err) {
                    newtouch_event_f4();
                    $('#zyh').trigger('focus');
                }
            });
    }

    //初始化病人信息
    function setPatInfoModel() {
        zyh = patModel.zyh;
        $('#zyh').val(patModel.zyh);
        $('#zy_xm').html(patModel.xm);
        $('#zy_xb').html($.getGender(patModel.xb));
        $('#zy_nl').html(getAgeFromBirthTime({ begin: patModel.csny }).text);
        $('#zy_ryzd').html(patModel.ryzdmc);
        $('#zy_csny').html(patModel.csny ? patModel.csny.substring(0, 10) : '');
        $('#zy_ryrq').html(patModel.ryrq ? patModel.ryrq.substring(0, 10) : '');

        //$('#startTime').html(patModel.ryrq ? patModel.ryrq.substring(0, 10) : '');
        $('#startTime').html(patModel.ryrq ? patModel.ryrq.replace('T',' '): '');
    }


    function hisSubmit(isYbjyjz, ybjyFeeReturn) {
        var zyh = patModel.zyh;
        var ryrq = $.getDate({ date: patModel.ryrq });
        var zje = ovpraseFloat(jszje).toFixed(2);
        //
        var widthpx = "700px";
        var heightpx = "550px";
        var hzjslx = "0";//0自费  1医保  8农保
        if (isYbjyjz && ybjyFeeReturn) {
            sessionStorage.setItem('ybjyFeeReturn', JSON.stringify(ybjyFeeReturn));
            sessionStorage.setItem('cqPatInfo', JSON.stringify(cqPatInfo));
            widthpx = "700px";
            heightpx = "600px";
            hzjslx = "1";
            ybjyFeeReturn.cqtczf = ybjyFeeReturn.hifp_pay;
            ybjyFeeReturn.zhzf = ybjyFeeReturn.acct_pay;
            ybjyFeeReturn.cqxjzf = ybjyFeeReturn.psn_cash_pay;
            ybjyFeeReturn.gwybz = ybjyFeeReturn.cvlserv_pay;
            ybjyFeeReturn.delpje = ybjyFeeReturn.hifob_pay;
            ybjyFeeReturn.dbzddyljgdz = ybjyFeeReturn.hosp_part_amt;
            ybjyFeeReturn.zhye = ybjyFeeReturn.balc;
            ybjyFeeReturn.jylsh = ybjyFeeReturn.setl_id;
            ybjyFeeReturn.zxjssj = ybjyFeeReturn.setl_time;
        }

        var openUrl = "/HospitalizationManage/DischargeSettle/SettConfirmForm?zyh=" + zyh;
        openUrl += "&ryrq=" + (!!ryrq ? ryrq : '');
        openUrl += "&zje=" + (!!zje ? ovpraseFloat(zje).toFixed(2) : '');
        openUrl += "&xjzfys=" + (!!zje ? ovpraseFloat(zje).toFixed(2) : '');
        openUrl += "&patid=" + patModel.patId;
        openUrl += "&isXnhjy=";
        openUrl += "&isYbjy=" + (!!isYbjyjz) + "&brxz=" + patModel.brxz + "&brxzmc=" + patModel.brxzmc+ "&ztjs=" + true,
            $.modalOpen({
                id: "ConfirmFeeForm",
                title: "中途结算",
                url: openUrl,
                width: widthpx,
                height: heightpx,
                callBack: function (iframeId) {
                    top.frames[iframeId].AcceptClick(function (feeRelated, outTradeNo) {
                        var startTime = $('#startTime').html();
                        if (!!!startTime) {
                            $.modalAlert("未指定结算开始时间", 'error');
                            return;
                        }
                        if (!!!zyh) {
                            $.modalAlert("请选择住院病人", 'error');
                            return;
                        }
                        var thisSettEndTime = $('#endTime').val();
                        if (!!!thisSettEndTime) {
                            $.modalAlert("未指定结算结束时间", 'error');
                            return;
                        }

                        if ($("#startTime").val() > $("#endTime").val()) {
                            $.modalAlert("开始时间不能大于结束时间", "warning");
                            return;
                        }

                        var allLine = $("#gridList").jqGrid('getRowData_AllLine', null, true);
                        if (!!!allLine || allLine.length == 0) {
                            $.modalAlert("无未结费用", 'error');
                            return;
                        }
                       
                        //提交
                        feeRelated.ver = "2";
                        var postData = { zyh: zyh, startTime: startTime, endTime: thisSettEndTime, fph: feeRelated.fph, feeRelated: feeRelated, ybfeeRelated: ybjyFeeReturn, jslx: hzjslx, outTradeNo: outTradeNo };
                        $.submitForm({
                            type: "POST",
                            url: "/HospitalizationManage/DischargeSettle/PartialSettleSave",
                            param: postData,
                            success: function (ajaxresp) {
                                var message = "";
                                sessionStorage.setItem('zyh', zyh);

                                $.modalMsg("结算成功" + message, 'success');
                                $.modalClose("ConfirmFeeForm");
                                if (isYbjyjz)
                                {
                                    var jsnm ="";
                                    if (ajaxresp.data && ajaxresp.data.jsnm) {
                                        jsnm = ajaxresp.data.jsnm;
                                    }
                                    $.ajax({
                                        type: "POST",
                                        url: "/HospitalizationManage/DischargeSettle/ExecPartialSettleDeatil",
                                        data: { zyh: zyh, jsnm: jsnm, czlx: "mofify" },
                                        dataType: "json",
                                        cache: false,
                                        async: false,
                                        success: function (refdate) {
                                        }
                                    });
                                }
                                newtouch_event_f4();
                                //打印发票
                                if (ajaxresp.data && ajaxresp.data.jsnm) {
                                    if ('@(autoPrintFP)' == 'True') {
                                        //报表打印
                                        var uri = '@Html.Raw(invoiceReportUrl)' + "&jsnm=" + ajaxresp.data.jsnm;
                                        window.open(uri, "_blank", "height=500, width=1195,top=100, left=50, toolbar =no, menubar=no, scrollbars=yes, resizable=yes, location=no, status=no");

                                    }
                                }
                            }
                        });
                    });
                },
                cancelCallBack: function (iframeId) {
                    //取消出院结算，出院办理回退
                    if (isYbjyjz) {
                            var cqybjyDenySettleReturn;
                            var payoptype = { hisId:zyh,'setl_id': ybjyFeeReturn.setl_id, 'operatorId': '@(opr.rygh)', 'operatorName': '@(opr.UserName)', 'mdtrt_id': ybjyFeeReturn.mdtrt_id, 'psn_no': cqPatInfo.grbh, "insuplc_admdvs": cqPatInfo.xzqh };
                            $.ajax({
                                type: "POST",
                                url: "http://127.0.0.1:33333/api/YiBao/HospitaUpSettlement_2305",
                                dataType: "json",
                                data: payoptype,
                                async: false,
                                success: function (data) {
                                    cqybjyDenySettleReturn = eval('(' + data + ')');
                                }
                            });
                            if (cqybjyDenySettleReturn.infcode !== "0") {
                                $.modalAlert('住院结算冲正失败：' + cqybjyDenySettleReturn.err_msg + '【此时医保已经结算成功，请联系his开发商处理】', 'error');
                            }

                            $.loading(false);
                    }
                }
            });
    }

    function newtouch_event_f4() {
        $('#zyh').val('');
        sessionStorage.removeItem('zyh');
        $('#startTime').html('');

        $('#endTime').val('@(yesterday)');
        $('#zy_xm').html('');
        $('#zy_xb').html('');
        $('#zy_nl').html('');
        $('#zy_ryzd').html('');
        $('#zy_csny').html('');
        $('#zy_ryrq').html('');
        patModel = null;
        jszje = 0.00;
        flagIsFirstInitGrid2 = true;
        $('#myTab li:eq(1) a').tab('show'); //会触发grid2加载样式
        $('#lblSumje').text('0.00');
        $('#gridList').jqGrid("clearGridData");
        $('#gridList2').jqGrid("clearGridData");
        zyh = "";
    }


    //撤销结算
    function newtouch_event_f6() {
        if (!zyh) {
            $.modalAlert("住院号为空，请确认", 'warning');
            return;
        }
        $.ajax({
            type: "GET",
            url: "/HospitalizationManage/DischargeSettle/GetCQLastjsnm?zyh=" + zyh,
            dataType: "json",
            async: false,
            success: function (jsnm) {
                if (isYbjyjz) {
                    if (!ybIsReadCard) {
                        $.modalAlert("医保患者取消结算，请先读卡！", 'warning');
                        return;
                    }
                        var cqybjyDenySettleReturn;
                        $.ajax({
                            type: "GET",
                            url: "/HospitalizationManage/DischargeSettle/GetCancelSettInfo?jsnm=" + jsnm,
                            dataType: "json",
                            async: false,
                            success: function (canceldata) {
                                if (canceldata) {
                                    $.ajax({
                                        type: "POST",
                                        url: "http://127.0.0.1:33333/api/YiBao/HospitaUpSettlement_2305",
                                        dataType: "json",
                                        data: canceldata,
                                        async: false,
                                        success: function (data) {
                                            cqybjyDenySettleReturn = eval('(' + data + ')');
                                        }
                                    });
                                    if (cqybjyDenySettleReturn.infcode == "0") {
                                        Docancelhissubmit(jsnm, cqybjyDenySettleReturn.output.setlinfo);
                                        $.ajax({
                                            type: "POST",
                                            url: "/HospitalizationManage/DischargeSettle/ExecPartialSettleDeatil",
                                            data: { zyh: zyh, jsnm: jsnm, czlx: "delete" },
                                            dataType: "json",
                                            cache: false,
                                            async: false,
                                            success: function (refdate) {
                                            }
                                        });
                                    } else {
                                        $.modalAlert('住院结算冲正失败：' + cqybjyDenySettleReturn.err_msg + '【此时医保已经结算成功，请联系his开发商处理】', 'warning');
                                        return;
                                    }
                                } else {
                                    $.modalAlert('取消结算失败，结算表cqyb_OutPut05中无该次结算医保落地数据：结算内码' + jsnm, 'warning');
                                    return;
                                }
                                $.loading(false);
                            }
                        });
                } else {
                    Docancelhissubmit(jsnm);
                }
            }
        });
    }

    //转出院结算
    function newtouch_event_f7() {
        $.najax({
            url: "/HospitalizationManage/DischargeSettle/TransfertoCYsettle?zyh=" + zyh,
            success: function (ajaxresp) {
                var ybresp = { zyh: zyh, jslsh: ajaxresp.data };
                $.ajax({
                    type: "POST",
                    url: "http://127.0.0.1:33333/api/CQYiBao/UpdateSettType",
                    dataType: "json",
                    data: ybresp,
                    async: false,
                    success: function (data) {
                        var medicalReg = eval('(' + data + ')');
                        if (medicalReg) {
                            if (medicalReg.Code === "1") {
                                $.loading(false);
                                $.modalMsg("结算成功", 'success');
                                newtouch_event_f4();
                            }
                            else {
                                $.loading(false);
                                $.modalAlert("医保住院修改就诊登记失败：" + medicalReg.ErrorMsg, 'error');
                                return;
                            }
                        }
                    }
                });
            },
        });
    }

    //结算
    function newtouch_event_f8() {
        if (!!!zyh || !!!$('#zyh').val()) {
            $.modalAlert("请选择住院病人", 'error');
            return;
        }

        var startTime = $('#startTime').html();
        if (!!!startTime) {
            $.modalAlert("未指定结算开始时间", 'error');
            return;
        }
        if (!!!zyh) {
            $.modalAlert("请选择住院病人", 'error');
            return;
        }
        var thisSettEndTime = $('#endTime').val();
        if (!!!thisSettEndTime) {
            $.modalAlert("未指定结算结束时间", 'error');
            return;
        }

        if (startTime > thisSettEndTime) {
            $.modalAlert("开始时间不能大于结束时间", "warning");
            return;
        }
        var allLine = $("#gridList").jqGrid('getRowData_AllLine', null, true);
        if (!!!allLine || allLine.length == 0) {
            $.modalAlert("无未结费用", 'error');
            return;
        }


        if (isYbjyjz) {//医保
            if (!medicalInsurance) {
                $.modalAlert("程序未动态配置医保地，请配置后重试", 'warning');
                return;
            }
                if (!ybIsReadCard) {
                    $.modalAlert("医保患者结算，请先读卡！", 'warning');
                    return;
                }
                $.loading(true, '正在进行就诊登记修改，请稍后...');
                setTimeout(function() {
                    CQjzdj(function (jzxx) {
                            $.loading(true, '正在验证费用明细，请稍后...');
                            setTimeout(function() {
                                CQmxsc(jzxx,
                                        function (mxxx) {
                                            $.loading(true, '正在进行医保结算，请稍后...');
                                            setTimeout(function() {
                                                CQybjs(jzxx, mxxx);
                                                });
                                        });
                                },
                                50);
                        });
                    },
                    50);
        }
        else
        {
            hisSubmit();
        }
    }

    //本地操作取消结算
    function Docancelhissubmit(jsnm,ybBackReturnData)
    {
        var allLine = $("#gridList2").jqGrid('getRowData_AllLine', null, true);
        if (!!!allLine || allLine.length == 0) {
            $.modalAlert("无历史已结", 'error');
            return;
        }
        ybCommonBackReturnData = ybBackReturnData;
        $.modalOpen({
            id: "refundForm",
            title: "退费详情",
            url: "/HospitalizationManage/DischargeSettle/CancelPartialConfirmForm?jsnm=" + jsnm + "&patid=" + patModel.patId,
            width: "300px",
            height: "350px",
            callBack: function (iframeId) {
                top.frames[iframeId].submitform(); //在弹出窗口事件
            }
        });
    }

    function CancelTheLastMidwaySett(zffs1, zffsmc1,jsnm) {
        var postData = { zyh: zyh, zffs1: zffs1, zffsmc1: zffsmc1 };
        $.submitForm({
            type: "POST",
            url: "/HospitalizationManage/BookkeepInHos/CancelTheLastMidwaySett",
            param: postData,
            success: function (ajaxresp) {
                sessionStorage.setItem('zyh', zyh);
                sessionStorage.setItem('defaultShow', 'yj');
                if (isYbjyjz) {
                        ybCommonBackReturnData.jsnm = jsnm;
                        $.najax({
                            type: "POST",
                            data: {
                                entity: ybCommonBackReturnData, jslb: "4"
                            },
                            url: "/OutpatientManage/OutpatCharge/SaveChongQing99HQ",
                            dataType: "json",
                            loading: false,
                            success: function () {
                                newtouch_event_f4();
                            }
                        });
                } else {
                    newtouch_event_f4();
                }
            },
        });
    }

</script>
<script type="text/javascript">

    //重庆医保
    function CQjzdj(funcSuccCallback) {
	     $.ajax({
		    type: "POST",
		    url: "/PatientManage/HospiterRes/GetCQjzdjInfo",
		    data: { zyh: patModel.zyh },
		    dataType: "json",
		    cache: false,
		    async: false,
		    success: function (payoptype) {
		    	if (!payoptype) {
				    $.loading(false);
				    $.modalAlert("获取住院就诊登记失败", 'error');
				    return;
		    	}
		    	payoptype.mdtrt_cert_type = cqPatInfo.ybklx;
		    	payoptype.orgId = "@opr.OrganizeId";
		        //var jzxx = { mdtrt_id: payoptype.mdtrt_id, med_type: payoptype.med_type, djxx: payoptype };
		        //funcSuccCallback(jzxx);
		        $.ajax({
		            type: "POST",
		            url: "http://127.0.0.1:33333/api/YiBao/HospitaMdtrtinfo_2403",
		            dataType: "json",
		            data: payoptype,
		            async: false,
		            success: function (data) {
		                var medicalReg = eval('(' + data + ')');
		                if (medicalReg) {
		                    if (medicalReg.infcode == "0") {
		                        var jzxx = { mdtrt_id: payoptype.mdtrt_id, med_type: payoptype.med_type, djxx: payoptype };
		                        funcSuccCallback(jzxx);
		                    }
		                    else {
		                        $.loading(false);
		                        $.modalAlert("住院信息变更失败：" + medicalReg.err_msg, 'error');
		                        return;
		                    }
		                }
		            }
		        });
		    }
	    });
    }
   
    function CQmxsc(jzxx,funcSuccCallback) {
        var n = 1;
        var ybzje = 0.00;
        var succTimes = 0;
        var mxnum = 0;
        var isuccer = true;//明细上传是否成功
        //var zfzje = 0.00;
        var cyrq;

	    $.najax({
	        type: "GET",
	        data: {
	            zyh: patModel.zyh, jssj: $('#endTime').val(), jsbz:"2"
	        },
	        url: "/HospitalizationManage/DischargeSettle/ValialUploadData",
	        dataType: "json",
	        async: false,
	        loading: false,
	        success: function (ajaxResp) {
	            var jfbh = ajaxResp.jfbh;
	            var zjjfbh = ajaxResp.zjjfbh;
	            if (jfbh) {
	                $.loading(false);
	                isuccer = false;
	                $.modalAlert(jfbh + "未上传至医保,请至预结算页面查询并进行上传!", 'error');
	                return;
	            }
	            else if (zjjfbh)
	            {
	                $.loading(false);
	                isuccer = false;
	                $.modalAlert("中途结算只能上传所选结算时间之前的费用明细,请至预结算页面选择需中途结算时间并进行上传!,计费编号:"+zjjfbh , 'error');
	                return;
	            }
	            else {
	                $.najax({
	                    type: "GET",
	                    data: {
	                        mzzyh: patModel.zyh, jssj: $('#endTime').val()
	                    },
	                    url: "/HospitalizationManage/DischargeSettle/GetCQAlreadyUploadFeeDetailsV2",
	                    dataType: "json",
	                    async: false,
	                    loading: false,
	                    success: function (ajaxResp) {
	                        ybzje = ajaxResp.ybzje;
	                        cyrq = ajaxResp.csrq;
	                    }
	                });
	            }
	        }
	    });
        $.loading(false);
        if (funcSuccCallback && isuccer) {
            setTimeout(function () {
                var mxxx = { ybzje: ybzje ,cyrq:cyrq};
                funcSuccCallback(mxxx);
            }, 50);
        }
    }
    function CQybjs(jzxx,mxxx) {
        var jzlx = cqPatInfo.ybklx
        var predata = {
            psn_no: cqPatInfo.grbh,
            mdtrt_cert_type: cqPatInfo.ybklx,
            mdtrt_cert_no: jzlx == "01" ? cqPatInfo.ecToken : (jzlx == "02" ? cqPatInfo.sfzh : cqPatInfo.sbkh),
            medfee_sumamt: mxxx.ybzje,
            psn_setlway: "01",
            mdtrt_id: jzxx.mdtrt_id,
            insutype: cqPatInfo.xzlx,
            mid_setl_flag: "1",
            insuplc_admdvs: cqPatInfo.xzqh,
            operatorId: '@(opr.rygh)',
            operatorName: '@(opr.UserName)',
            hisId: patModel.zyh,
            acct_used_flag: "1",
            dscgTime: $('#endTime').val().substring(0, 10)//mxxx.cyrq
        };
        var ybjsSettReturn1;
        var ybjsSettReturn;
        $.ajax({
            type: "POST",
            url: "http://127.0.0.1:33333/api/YiBao/HospitaSettlement_2303",
            data: predata,
            dataType: "json",
            async: false,
            success: function (data) {
                ybjsSettReturn1 = eval('(' + data + ')');
            }
        });
        if (ybjsSettReturn1) {
            if (ybjsSettReturn1.infcode == "0") {
                $.ajax({
                    type: "POST",
                    url: "http://127.0.0.1:33333/api/YiBao/HospitaSettlement_2304",
                    data: predata,
                    dataType: "json",
                    async: false,
                    success: function (data) {
                        ybjsSettReturn = eval('(' + data + ')');
                    }
                });
                if (ybjsSettReturn) {
                    $.loading(false);
                    if (ybjsSettReturn.infcode == "0") {
                        var ybjyCqFeeReturn = ybjsSettReturn.output.setlinfo;
                        //his结算确认（包括医保结算确认）
                        //根据后台查询出的结果，如果该患者有开立自立的项目（没有医保代码），则结算时的总金额，填写总的汇总金额
                        //如果只有医保项目，则以医保结算的医保返回结果为准进行结算
                        ybjyCqFeeReturn.his_hisfyze = jszje;
                        ybjyCqFeeReturn.ybzje = mxxx.ybzje;
                        ybjyCqFeeReturn.jzid = jzxx.mdtrt_id;
                        hisSubmit(true, ybjyCqFeeReturn, false, null);
                       
                    } else {
                        $.loading(false);
                        $.modalAlert(ybjsSettReturn.err_msg, 'error');
                        return;
                    }
                } else {
                    $.loading(false);
                    $.modalAlert("调用医保接口失败", 'error');
                    return;
                }
            } else {
                $.loading(false);
                $.modalAlert(ybjsSettReturn1.err_msg, 'error');
                return;
            }
        } else {
            $.loading(false);
            $.modalAlert("调用医保接口【2303】预结算失败,请重试!", 'error');
            return;
        }

    }
    function upLoadReturnData(retdata) {
        $.najax({
            url: '/HospitalizationManage/DischargeSettle/upLoadReturnData',
            data: { upReturnData: retdata, patzyh: zyh },
            type: 'POST',
            success: function () {

            }
        });
    }
    //查询条件
    function getSearchPostData(n) {
        var zyh = patModel.zyh;
        var pagination = {
            rows: 50,
            page: n + 1,
            sidx: 'yka105 asc'
        };
        return { pagination: pagination, zyh: zyh };

    }
    //查询条件
    function getSearchCQPostData(n) {
	    var zyh = patModel.zyh;
	    var pagination = {
	        rows: 10,
	        page: 1,
		    //page: n + 1,
		    sidx: ' cxmxlsh asc'
	    };
	    return { pagination: pagination, zyh: zyh };

    }
    function ovpraseFloat(val) {
        if (!val) {
            val = 0.00;
        }
        return parseFloat(val);
    }
    //获取结算患者 患者信息
    function funcGetSettPatientInfo(funcSuccCallback) {
        $.najax({
            url: '/HospitalizationManage/DischargeSettle/GetInpatientSettYbPatInfo?zyh=' + patModel.zyh,
            loadingtext: "正在请求患者出院信息，请稍后...",
            type: 'POST',
            success: function (ajaxResp) {
                //
                if (funcSuccCallback) {
                    setTimeout(function () {
                        funcSuccCallback(ajaxResp.data);
                    }, 50);
                }
            }
        });
    }
</script>
<script type="text/javascript">
    //医保读卡
    function ReadCardCall(readCardObj) {
        debugger;
        cqPatInfo.jslx = "2";
        ybIsReadCard = true;
        ajaxLoadDataResult({ kh: readCardObj.yibaoCardInfo.kh, sfz: readCardObj.yibaoCardInfo.qtjz, cardType: readCardObj.ybkCardType, ver: '2' });
    }
</script>
